// plugin/components/indexes/index.js
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    /**
   * 是否开启跳转过渡动画
   * @default false
   */
    animation: {
      type: Boolean,
      value: false
    },
    /**
     * 右侧导航第一个名称
     * @default Top
     */
    topKey: {
      type: String,
      value: ''
    },
    /**
     * 是否切换 key 的震动
     * **注意：** 只在微信小程序有效
     * @default true
     */
    isVibrate: {
      type: Boolean,
      value: false
    },
    /**
     * 是否用弹框显示当前 key
     * @default true
     */
    isShowToast: {
      type: Boolean,
      value: true
    },
    /**
     * 列表
     */
    list: {
      type: Array,
      value: () => []
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    startTop: 0,
    menuHeight: 0,
    _scrollTop: 0,
    currentIndex: -1,
    _isShowToast: false,
    _tipText: '',
    _scrollIntoView: '',
    itemHeight: 0,

    timeoutTimer: undefined
  },
  ready () {
    const that = this
    // 加个定时器，防止数据还未渲染完成，获取错误宽高
    setTimeout(() => {
      that._initData()
    }, 1000);
  },
  detached: () => {
      clearTimeout(timeoutTimer)
  },
  /**
   * 组件的方法列表
   */
  methods: {
    /**
     * 初始化数据，获取索引菜单的高度等信息
     */
    _initData () {
      const that = this
      const querySelctor = wx.createSelectorQuery().in(this)
      querySelctor
      .select('.at-indexes__menu')
      .boundingClientRect()
      .exec(rect => {
          const { list } = this.data
          if(rect && rect[0]) {
            const menuHeight = rect[0].height
            const startTop = rect[0].top
            const itemHeight = Math.floor(menuHeight / (list.length + 1))
            that.setData({
              menuHeight,
              startTop,
              itemHeight
            })
          }
      })
  },
    handleScroll: function(e) {
      if (e && e.detail) {
          this.setData({
              _scrollTop: e.detail.scrollTop
          })
      }
    },

    handleTouchStart: function() {

    },
    handleTouchMove: function(event) {
      const that = this
      // event.stopPropagation()
      // event.preventDefault()
      const itemHeight = that.data.itemHeight
      if (!itemHeight) {
        console.warn('未能正确获取到索引选择器的宽高：', itemHeight)
        return
    }
      const { list } = that.data
      const pageY = event.touches[0].pageY

      const index = Math.floor((pageY - that.data.startTop) / itemHeight)

      if (index >= 0
          && index <= list.length
          && that.data.currentIndex !== index
      ) {
          that.data.currentIndex = index
          const key = index > 0 ? list[index - 1].key : 'top'
          const touchView = `at-indexes__list-${key}`
          that._jumpTarget(touchView, index)
      }
    },
    handleTouchEnd: function() {
      this.setData({
        currentIndex: -1
      })
    },
    jumpTarget: function(e) {
      const target = e.currentTarget.dataset.target
      const index = e.currentTarget.dataset.index
      this._jumpTarget(target, index)
    },
    _jumpTarget: function(_scrollIntoView, idx) {
      const { topKey, list } = this.properties
      const _tipText = !idx || idx === 0 ? topKey : list[idx - 1].key

      this.updateState({
        _tipText,
        _scrollIntoView
      })

    },

    updateState: function(state) {
      const { isShowToast, isVibrate } = this.data
      const { _scrollIntoView, _tipText, _scrollTop } = state
      // TODO: Fix dirty hack
      this.setData({
          _scrollIntoView: _scrollIntoView,
          _tipText: _tipText,
          _scrollTop: _scrollTop || 0,
          _isShowToast: isShowToast
      }, () => {
          clearTimeout(this.data.timeoutTimer)
          this.data.timeoutTimer = setTimeout(() => {
              this.setData({
                  _tipText: '',
                  _isShowToast: false
              })
          }, 3000)
      })

      if (isVibrate) {
        wx.vibrateShort()
      }
    },

    handleClick: function(e) {
      const item = e.currentTarget.dataset.item
      this.triggerEvent('click', item)
    }
  },

  lifetimes: {
    
    attached: function() {
      // const that = this
      // setTimeout(() => {
      //   that.initData()
      // }, 300)
    },
    detached: function() {
      // 在组件实例被从页面节点树移除时执行
    },
  
    error: function() {
      this.setData({
        errorState: true
      })
    }
  }
})
